package adapter.common
{
	import ui.common.CellBase;
	import ui.common.GridBase;

	/**
	 * @author Administrator
	 */
	public class GridBaseAdapter extends AdapterBase
	{
		private var _selectIndex:int = -1;
		
		private var _cellAdptArr:Array = [];
		
		public function GridBaseAdapter()
		{
		}
		
		protected function get grid():GridBase
		{
			return ui as GridBase;
		}
		
		public function get cellAdptClass():Class
		{
			return CellBaseAdapter;
		}
		
		override protected function onUIAttach():void
		{
			var i:int;
			var cell:CellBase;
			var cellAdpt:CellBaseAdapter;
			
			super.onUIAttach();
			
			createCellAdapterArr();
			if(grid)
			{
				for(i=0; i<grid.length; i++)
				{
					cell = grid.getAt(i);
					cellAdpt = _cellAdptArr[i] as CellBaseAdapter;
					
					if(cell && cellAdpt)
					{
						cellAdpt.index = i;
						cellAdpt.parentAdpater = this;
						cellAdpt.attachUI(cell);
					}
				}
			}
		}
		
		override protected function onUIDeattach():void
		{
			clear();
			
			super.onUIDeattach();
		}
		
		
		protected function createCellAdapterArr():void
		{
			var i:int;
			
			clear();
			if(grid && cellAdptClass)
			{
				for(i=0; i<grid.length; i++)
				{
					_cellAdptArr.push(new cellAdptClass);
				}
			}
		}
		
		public function onSelectItem(index:int):void
		{
			selectedIndex = index;
		}
		
		public function get selectedIndex():int
		{
			return _selectIndex;
		}
		
		public function set selectedIndex(index:int):void
		{
			var cellBaseAdpt:CellBaseAdapter;
			
			if(index == _selectIndex)
			{
				return;
			}
			
			cellBaseAdpt = _cellAdptArr[_selectIndex] as CellBaseAdapter;
			if(cellBaseAdpt)
			{
				cellBaseAdpt.onUnselect();
			}
			
			_selectIndex = index;
			cellBaseAdpt = _cellAdptArr[_selectIndex] as CellBaseAdapter;
			if(cellBaseAdpt)
			{
				cellBaseAdpt.onSelect();
			}
		}
		
		public function get length():int
		{
			if(_cellAdptArr)
			{
				return _cellAdptArr.length;
			}
			
			return 0;
		}
		
		public function getAt(i:int):CellBaseAdapter
		{
			if(!_cellAdptArr)
			{
				return null;
			}
			
			return _cellAdptArr[i] as CellBaseAdapter;
		}
		
		private function clear():void
		{
			var i:int;
			var cellAdpt:CellBaseAdapter;
			
			for(i=0; i<_cellAdptArr.length; i++)
			{
				cellAdpt = _cellAdptArr[i] as CellBaseAdapter;
				if(cellAdpt)
				{
					cellAdpt.deattachUI();
				}
			}
			
			_cellAdptArr.length = 0;
		}
		
		public function get menuAdpt():MenuBaseAdapter
		{
			return null;
		}
		
		public function get tooltipAdpt():TooltipBaseAdapter
		{
			return null;
		}
	}
}
